package com.jiyun.filter;

import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.api.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/* *
 * @Author nxj
 * @Date 2023 07 2023/7/31 18 42
 * */
@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String loginPageUrl="/login";
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        String path = request.getURI().getPath();
        log.info("url:是{}",path);
        //||path.contains("/js")||path.contains("/css")||path.contains(".html")
        if(path.contains(loginPageUrl)||path.contains("uploadFile")||path.contains("export")||path.contains("import")){
            log.info("本次访问是登录页面");
            return chain.filter(exchange);
        }else {
            String token = getToken(request);
            if(StringUtils.isBlank(token)){
             response.setStatusCode(HttpStatus.UNAUTHORIZED);
             return response.setComplete();
            }else {
                try {
                    boolean b = JWTUtil.verify(token, "1".getBytes());
                    if(b){
                        return chain.filter(exchange);
                    }else {
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        return response.setComplete();
                    }

                }catch (Exception e){
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    return response.setComplete();
                }
            }
        }


    }

    @Override
    public int getOrder() {
        return 1;
    }
    public String getToken(ServerHttpRequest request){
//        String token = request.getQueryParams().getFirst("token");
        String token = request.getHeaders().getFirst("token");
        log.info("token:{}",token);
        return token;
    }
}
